package com.gemme.gemme.login;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.gemme.gemme.MainActivity;
import com.gemme.gemme.R;
import com.gemme.gemme.manager.DataManager;
import com.gemme.gemme.view.GeButton;

import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
/*
* 先获取验证码,后点击按钮登录
* */
public class MsgActivity extends AppCompatActivity {
    Context context =  this;
    public   int type = type_tel;
    public static final String TYPE = "type";
    public static final int type_tel = 0;
    public static final int type_weixin = 1;
    public static final int type_weibo = 2;
    String account;
    String yqm_code;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_msg);
        getData();
        initView();
    }
    GeButton gebt;
    TextView des2;
    EditText acount;
    private void initView() {
        gebt = findViewById(R.id.gebt);
        des2 = findViewById(R.id.des2);
        acount = findViewById(R.id.acount);
        gebt.setText("登录");
        if(TextUtils.isEmpty(account)){
            Toast.makeText(context,"手机号不能为空",Toast.LENGTH_SHORT);
            return;
        }else{
            des2.setText("我们已向"+account+"发送验证码，");
//            toMsg();

            if(type == type_tel){
                toMsg();

            }else if(type == type_weixin){
                toWeiXinMsg();
            }else if(type == type_weibo){

            }
        }



        gebt.findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(type == type_tel){
                    toLogin();

                }else if(type == type_weixin){
                    weixinSign();
                }else if(type == type_weibo){

                }

            }
        });
    }

    private void getData(){
        try {
            account = getIntent().getStringExtra("account");
            yqm_code = getIntent().getStringExtra("yqm_code");
            type = getIntent().getIntExtra(TYPE,type_tel);

        }catch (Exception e){

        }
    }

    private void toWeiXinMsg() {
        if(TextUtils.isEmpty(account)){
            Toast.makeText(context, "手机号不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        String url = DataManager.BaseUrl + "user/userapp/bindingsms?" +
                "smsType=" + "binding_wx"
                +"&mobile=" + account
                ;
        HashMap<String, String> headMap = new HashMap<>();
        DataManager.toServer3(context, url, DataManager.POST_TYPE, "", null, new DataManager.GeResponse() {
            @Override
            public void onResponse(String response) {
                try{
                    JSONObject jsonObject = new JSONObject(response);
                    boolean bindingsms = jsonObject.getBoolean("data");
                    msg = jsonObject.getString("msg");
                    System.out.println("");

                    if(TextUtils.isEmpty(msg)){
                        Toast.makeText(context, "验证码获取失败", Toast.LENGTH_SHORT).show();
                    }else{
                        Toast.makeText(context, "获取验证码成功", Toast.LENGTH_SHORT).show();
                    }

                    if(bindingsms ){//获取验证码成功
                        System.out.println("");
//                        weixinSign(msg);
                        acount.setText(msg);
                    }else{
                    }
                }catch (Exception e){

                }
            }
        });
    }

    private void weixinSign() {
        if(TextUtils.isEmpty(account)){
            Toast.makeText(context, "手机号不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if(TextUtils.isEmpty(msg)){
            Toast.makeText(context, "验证码不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        String url = DataManager.BaseUrl + "user/userapp/bindingmobile?" +
                "mobile=" + account
                +"&smsCode=" + msg
                ;
        ;
        HashMap<String, String> headMap = new HashMap<>();
        DataManager.toServer3(context, url, DataManager.POST_TYPE, "", null, new DataManager.GeResponse() {
            @Override
            public void onResponse(String response) {
                try{
                    JSONObject jsonObject = new JSONObject(response);
                    boolean bindingmobile = jsonObject.getBoolean("data");
                    System.out.println("");

                    if(bindingmobile){//绑定成功
                        Toast.makeText(context, "" + jsonObject.getString("msg"), Toast.LENGTH_SHORT).show();
                        toWeixinLogin();
                    }{
                        Toast.makeText(context, "" + jsonObject.getString("msg"), Toast.LENGTH_SHORT).show();
                    }


                }catch (Exception e){

                }
            }
        });
    }

    private void toWeixinLogin() {
        if(TextUtils.isEmpty(account)){
            Toast.makeText(context, "手机号不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        String weixin_openid = null;
        String weixin_accessToken = null;
        try {
            weixin_openid = getIntent().getStringExtra("weixin_openid");

            weixin_accessToken = getIntent().getStringExtra("weixin_accessToken");
        }catch (Exception e){

        }

        if(TextUtils.isEmpty(weixin_openid) || TextUtils.isEmpty(weixin_accessToken)){
            Toast.makeText(context, "缺少数据", Toast.LENGTH_SHORT).show();
            return;
        }


        String url = DataManager.BaseUrl + "auth/mobile/token/social?" +
                "phone=WX@" + weixin_openid
                +"&grant_type=" + "mobile"
                +"&access_token=" + weixin_accessToken
                +"&telephone=" + account
                +"&invite_code=" + (TextUtils.isEmpty(yqm_code) ? "":yqm_code)
                ;
        ;
        System.out.println("weixinlogin url :   " + url);
        HashMap<String, String> headMap = new HashMap<>();
        headMap.put("Authorization","Basic bW9iaWxlOm1vYmlsZQ==");
        DataManager.toServer3(context, url, DataManager.POST_TYPE, "", headMap, new DataManager.GeResponse() {
            @Override
            public void onResponse(String response) {
                try{
                    SharedPreferences MSP = context.getSharedPreferences(Constant.MSP, Context.MODE_PRIVATE);
                    UseInfoBean useInfos = JSON.parseObject(response,UseInfoBean.class);
                    if(!TextUtils.isEmpty(useInfos.getAccess_token()))
                        MSP.edit().putString(Constant.ACCESS_TOKEN, useInfos.getAccess_token()).apply();
                    if(!TextUtils.isEmpty(useInfos.getRefresh_token()))
                        MSP.edit().putString(Constant.REFRESH_TOKEN, useInfos.getRefresh_token()).apply();
                    if(!TextUtils.isEmpty(useInfos.getUser_info().getId()))
                        MSP.edit().putString(Constant.UserId, useInfos.getUser_info().getId() + "").apply();
                    MSP.edit().putString(Constant.ACCESS_TOKENTIME, System.currentTimeMillis() + "").apply();
                    MSP.edit().putString(Constant.REFRESH_TIME, System.currentTimeMillis() + "").apply();

                    startActivity(new Intent(context, MainActivity.class));
                    finish();
                }catch (Exception e){

                }
            }
        });
    }

    private void toLogin() {

        String url = DataManager.BaseUrl + "auth/mobile/token/sms?";
        if(TextUtils.isEmpty(account) || TextUtils.isEmpty(msg) ){
            Toast.makeText(context, "手机号和验证码不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        url = url + "phone=APPSMS@" + account
                +"&code=" + msg+
                "&grant_type="+ "mobile" +
                "&invite_code="+ (TextUtils.isEmpty(yqm_code) ? "":yqm_code)
        ;

        HashMap<String, String> hashmap = new HashMap<>();
        hashmap.put(DataManager.AuthorizationKey,DataManager.Authorization);
        DataManager.postDataToServerByHeader(context,url,"",hashmap,new DataManager.GeResponse() {
            @Override
            public void onResponse(String str) {
                try {
                    SharedPreferences MSP = context.getSharedPreferences(Constant.MSP, Context.MODE_PRIVATE);
                    UseInfoBean useInfos = JSON.parseObject(str,UseInfoBean.class);
                    if(!TextUtils.isEmpty(useInfos.getAccess_token()))
                        MSP.edit().putString(Constant.ACCESS_TOKEN, useInfos.getAccess_token()).apply();
                    if(!TextUtils.isEmpty(useInfos.getRefresh_token()))
                        MSP.edit().putString(Constant.REFRESH_TOKEN, useInfos.getRefresh_token()).apply();
                    if(!TextUtils.isEmpty(useInfos.getUser_info().getId()))
                        MSP.edit().putString(Constant.UserId, useInfos.getUser_info().getId() + "").apply();
                    MSP.edit().putString(Constant.ACCESS_TOKENTIME, System.currentTimeMillis() + "").apply();
                    MSP.edit().putString(Constant.REFRESH_TIME, System.currentTimeMillis() + "").apply();

                    startActivity(new Intent(context, MainActivity.class));
                    finish();
                }catch (Exception e){

                }
            }
        });

    }




    //12
    String msg;
    private void toMsg() {
//        String url = "http://192.168.1.6:9999/user/userapp/appmobile/15256987478";
        String url = DataManager.BaseUrl + "user/userapp/appmobile/" + account;
        DataManager.getDataFromServer(this, url, new DataManager.GeResponse() {
            @Override
            public void onResponse(String response) {
                System.out.println("");
                try {
                    MsgBean msgBean = JSON.parseObject(response, MsgBean.class);

                    msg = msgBean.getMsg();
                    acount.setText(msg);
                }catch (Exception e){

                }

            }
        });
    }
}